package com.qd.system.importexcel.orgperson;

import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.exception.ExcelOperatorException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.sys.domain.entity.org.OrgPersonDTO;
import com.qd.system.model.OrgPerson;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.org.OrgPersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 机构和人员,excel导入处理类
 *
 * @author sjk
 */
@Slf4j
public class OrgPersonImportHandler {

    private final OrgPersonService orgPersonService;
    private final ValidatorUtil validatorUtil;
    private final List<ImportErr> errorList;
    private final LocalDateTime now = LocalDateTime.now();

    public OrgPersonImportHandler(OrgPersonService orgPersonService, ValidatorUtil validatorUtil, List<ImportErr> errorList) {
        this.orgPersonService = orgPersonService;
        this.validatorUtil = validatorUtil;
        this.errorList = errorList;
    }

    /**
     * 处理具体导入
     *
     * @param rowList excel行数据集合，默认为1000行
     * @param results 异常信息存储
     */
    public void process(List<ExcelRowMsg<OrgPersonDTO>> rowList, List<BatchResult> results) {
        final List<OrgPersonDTO> orgPersonList = rowList.stream().map(ExcelRowMsg::getRowData).collect(toList());
        final List<String> personIds = orgPersonList.stream().map(OrgPersonDTO::getPersonId).filter(StringUtils::hasLength).collect(toList());
        final List<String> orgIds = orgPersonList.stream().map(OrgPersonDTO::getOrgId).filter(StringUtils::hasLength).collect(toList());
        final List<String> existsPersonIds = orgPersonService.getPersonService().getBaseMapper().getIds(personIds);
        final List<String> existsOrgIds = orgPersonService.getOrgService().getBaseMapper().getIds(orgIds);
        final List<String> existsIds = existsIds(orgPersonList);
        final List<String> existsOrgPersons = existsOrgPerson(existsPersonIds, existsOrgIds);
        final int size = rowList.size();
        try {
            for (ExcelRowMsg<OrgPersonDTO> excelRowMsg : rowList) {
                final OrgPersonDTO orgPersonDto = excelRowMsg.getRowData();
                final ReadRowHolder readRowHolder = excelRowMsg.getReadRowHolder();
                final List<String> errors = new ArrayList<>();
                importValidate(orgPersonDto, errors);
                importBaseColumn(orgPersonDto, existsOrgIds, existsPersonIds, existsOrgPersons, errors);
                if (!errors.isEmpty()) {
                    errorList.add(ExcelUtil.buildError(readRowHolder, errors));
                }
            }
            if (!errorList.isEmpty()) {
                throw new ExcelOperatorException(errorList);
            } else {
                final List<OrgPerson> addOrgPersonList = new ArrayList<>(size);
                final List<OrgPerson> updateOrgPersonList = new ArrayList<>(size);
                doProcessDictData(existsIds, orgPersonList, addOrgPersonList, updateOrgPersonList);
                BatchResult.buildBatchResult(results, addOrgPersonList.size(), updateOrgPersonList.size());
                addOrgPersonList.clear();
                updateOrgPersonList.clear();
            }
        } finally {
            orgPersonList.clear();
            existsIds.clear();
            existsOrgPersons.clear();
            personIds.clear();
            orgIds.clear();
            existsPersonIds.clear();
            existsOrgIds.clear();
        }
    }

    private void importBaseColumn(OrgPersonDTO orgPersonDto, List<String> existsOrgIds, List<String> existsPersonIds, List<String> existsOrgPersons, List<String> errors) {
        boolean isNotCheck = false;
        if (!MbUtil.isExistInCollection(existsPersonIds, orgPersonDto.getPersonId())) {
            errors.add("人员ID不存在[" + orgPersonDto.getPersonId() + "]");
            isNotCheck = true;
        }
        if (!MbUtil.isExistInCollection(existsOrgIds, orgPersonDto.getOrgId())) {
            errors.add("机构ID不存在[" + orgPersonDto.getOrgId() + "]");
            isNotCheck = true;
        }
        if (isNotCheck) {
            return;
        }
        if (MbUtil.isExistInCollection(existsOrgPersons, orgPersonDto.getPersonId())) {
            errors.add("机构和人员关系已经分配[" + orgPersonDto.getOrgId() + "|" + orgPersonDto.getPersonId() + "]");
        }
    }

    /**
     * 查询出已经存在的机构和人员关系
     *
     * @param personIds 人员ID集合
     * @param orgIds    人员机构ID集合
     * @return 已经存在的数据
     */
    private List<String> existsOrgPerson(List<String> personIds, List<String> orgIds) {
        if (personIds.isEmpty() || orgIds.isEmpty()) {
            return Collections.emptyList();
        }
        return orgPersonService.getBaseMapper().getOrgPersons(orgIds, personIds);
    }

    /**
     * 保存数据
     *
     * @param existsIds           已经存在的数据库主键
     * @param orgPersonList       excel行数据集合
     * @param addOrgPersonList    添加集合
     * @param updateOrgPersonList 更新集合
     */
    private void doProcessDictData(List<String> existsIds, List<OrgPersonDTO> orgPersonList, List<OrgPerson> addOrgPersonList, List<OrgPerson> updateOrgPersonList) {
        orgPersonList.forEach(orgPersonDto -> {
            final OrgPerson orgPerson = orgPersonService.dtoToModel(orgPersonDto);
            orgPersonService.clearCache(orgPerson);
            if (MbUtil.isExistInCollection(existsIds, orgPersonDto.getOrgPersonId())) {
                orgPerson.setAddTime(null);
                orgPerson.setUpdateTime(now);
                updateOrgPersonList.add(orgPerson);
            } else {
                orgPerson.setAddTime(now);
                orgPerson.setUpdateTime(null);
                addOrgPersonList.add(orgPerson);
            }
        });
        if (!addOrgPersonList.isEmpty()) {
            orgPersonService.saveBatch(addOrgPersonList);
        }
        if (!updateOrgPersonList.isEmpty()) {
            orgPersonService.updateBatchIds(updateOrgPersonList);
        }
    }

    /**
     * 获得主键存在的集合
     *
     * @param orgPersonList excel行数据集合
     * @return 主键集合
     */
    private List<String> existsIds(List<OrgPersonDTO> orgPersonList) {
        final List<String> ids = orgPersonList.stream().map(OrgPersonDTO::getOrgPersonId).collect(toList());
        final List<String> existsIds = orgPersonService.getBaseMapper().getIds(ids);
        ids.clear();
        return existsIds;
    }

    /**
     * 导入实体验证
     *
     * @param orgPersonDto 单个excel行数据
     * @param errors       异常信息存储
     */
    private void importValidate(OrgPersonDTO orgPersonDto, List<String> errors) {
        if (errors.isEmpty()) {
            try {
                validatorUtil.checkValid(orgPersonDto, DefaultGroup.class);
            } catch (ConstraintViolationException e) {
                errors.addAll(validatorUtil.getValidationError(e));
            }
        }
    }
}